package com.ddxz.demo.liquibase.configure;

import com.ddxz.demo.liquibase.mapper.TenantMapper;
import liquibase.integration.spring.SpringLiquibase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * 服务启动时，通过liquibase检测数据库的表结构是否是最新的，如果不是则通过指定的changeLog进行升级
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/12/16
 */

@Configuration
public class LiquibaseConfiguration {
    @Bean
    public SpringLiquibase springLiquibase(DataSource dataSource) throws SQLException {
        mapper.createTenant(supperTenant);
        SpringLiquibase springLiquibase = new SpringLiquibase();
        springLiquibase.setDataSource(dataSource);
        springLiquibase.setDefaultSchema(supperTenant);
        springLiquibase.setLiquibaseSchema(supperTenant);
        String dbType = dataSource.getConnection().getMetaData().getDatabaseProductName().toUpperCase();
        switch (dbType) {
            case "MYSQL":
                springLiquibase.setChangeLog("classpath:/liquibase/mysql-supper-tenant.xml");
                break;
            case "POSTGRESQL":
                springLiquibase.setChangeLog("classpath:/liquibase/postgres-supper-tenant.xml");
                break;
            case "ORACLE":
                springLiquibase.setChangeLog("classpath:/liquibase/oracle-supper-tenant.xml");
                break;
            case "Microsoft SQL Server":
                springLiquibase.setChangeLog("classpath:/liquibase/mssql-supper-tenant.xml");
                break;
            case "H2":
                springLiquibase.setChangeLog("classpath:/liquibase/h2-supper-tenant.xml");
                break;
            default:
                throw new SQLException("未知的数据库类型[" + dbType + "]");
        }

        return springLiquibase;
    }

    private final TenantMapper mapper;

    @Value("${ddxz.supper-tenant.name}")
    private String supperTenant;

    public LiquibaseConfiguration(TenantMapper mapper) {
        this.mapper = mapper;
    }
}
